<template>
	<view class="content">
		<!--		<page-meta>-->
		<!--			<navigation-bar background-color="#fff" navigationBarTextStyle="black"></navigation-bar>-->
		<!--		</page-meta>-->

		<view class="navTab">
			<block v-for="(item,index) in scrollList" :key="index">
				<view class="tab-item" :class="{'at-tab-item':current == index}" @click="tabChange(index)">
					{{item.name}}
				</view>
			</block>
			<view class="tab-bottom" :style="[{left:left+'px'},{width:width+'px'}]">
				<view class="xian" :style="{width:width/8+'px'}"></view>
			</view>
		</view>
		<swiper class="swiper" :current="current" @change="swiperChange">
			<swiper-item>
				<scroll-view scroll-y="true" class="scroll-view">
					<view class="box" :class="show ? 'fade-in' : 'fade-out'">
						<view class="title">
							<view class="title-left">充值海豚币</view>
							<view class="title-right" @click="goRecord">
								<text>充值记录</text>
								<!--<image src="/static/index/right3.png" mode=""></image>-->
								<text class="tn-icon-right"></text>
							</view>
						</view>
						<view class="price-list">
							<block v-for="(item,index) in cList" :key="index">
								<view class="p-list-item" :class="{'p-list-item-pitch':pIndex == index}"
									@click="xuanze(item.id,index,item.iap_product_id)">
									<view class="crystal">
										<image src="/static/index/priceIcon.png" mode=""></image>
										<text class="p1">{{item.xuni_money}}</text>
									</view>
									<view class="price">
										￥{{$isIos ? item.ios_money : item.money}}
									</view>
									<view class="tag" v-if="item.song_money > 0">赠送{{item.song_money}}</view>
								</view>
							</block>

						</view>

						<view v-if="$isAndroid" class="pay-list bg-color m-top">
							<view class="title">支付方式</view>
							<view class="list">
								<view class="item tn-flex tn-flex-col-center tn-flex-row-between" @click="selectPay(1)">
									<view class="item-left tn-flex tn-flex-col-center">
										<image src="/static/index/wx.png" class="wxIcon" mode=""></image>
										<text>微信支付</text>
									</view>
									<view class="item-right">
										<image src="/static/index/pitchon.png" mode="" v-if="payIndex == 1"></image>
										<image src="/static/index/unselected.png" mode="" v-else></image>

									</view>
								</view>
								<!-- #ifndef MP-WEIXIN -->
								<view class="item tn-flex tn-flex-col-center tn-flex-row-between" @click="selectPay(2)">
									<view class="item-left tn-flex tn-flex-col-center">
										<image src="/static/index/alipay.png" class="alipayIcon" mode=""></image>
										<text>支付宝支付</text>
									</view>
									<view class="item-right">
										<image src="/static/index/pitchon.png" mode="" v-if="payIndex == 2"></image>
										<image src="/static/index/unselected.png" mode="" v-else></image>
									</view>
								</view>
								<!-- #endif -->

							</view>
						</view>

						<payNotice />
						<view class="btn" @click="submitPay">立即充值</view>
						<view class="" style="height: 88rpx;"></view>
					</view>
				</scroll-view>
			</swiper-item>
			<swiper-item>
				<scroll-view scroll-y="true" class="scroll-view">
					<view class="box1">
						<view class="earnings-kuai">
							<view class="title">
								<text class="title-left">海豚币</text>
								<view class="title-right" @click="goEarnings">
									<text class="t1">收益明细</text>
									<image src="/static/index/right3.png" mode=""></image>
								</view>
							</view>
							<view class="price">{{my_moneynum}}</view>
							<view class="integral">积分：{{my_scorenum}}</view>
						</view>
						<template v-if="!isAuditMode">
							<view class="label">提现金额</view>
							<view class="input">
								<input type="text" placeholder="请输入提现金额" v-model="fData.ti_money"
									placeholder-class="p-class" />
							</view>
							<view class="label">提现账号</view>
							<view class="input">
								<input type="text" placeholder="请输入提现账号" v-model="fData.ti_kano"
									placeholder-class="p-class" />
							</view>
							<view class="label">提现姓名</view>
							<view class="input">
								<input type="text" placeholder="请输入提现姓名" v-model="fData.ti_name"
									placeholder-class="p-class" />
							</view>
							<view class="caution">温馨提示：1海豚币=1元，额外扣除￥0.1服务费（费率0.10%）</view>
							<!-- <view class="pay-title">提现到</view> -->
							<!-- <view class="pay-list">
							<image src="/static/my/wx.png" class="left-icon" mode=""></image>
							<view class="pay-center">
								<view class="pay-label">微信零钱</view>
								<view class="pay-value" @click="goAddAccout">
									<text>请先添加账户</text>
									<image src="/static/my/right.png" mode=""></image>
								</view>
							</view>
							<image src="/static/index/pitchon1.png" class="right-icon" mode=""></image>
						</view> -->
							<view class="t-detail" @click="goWithdrawal">
								<text>提现明细</text>
								<text class="tn-icon-right"></text>
								<!--							<image src="/static/my/right1.png" mode=""></image>-->
							</view>
							<view class="btn" @click="submitTi">立即提现</view>
						</template>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>
<script>
	import applePay from "@/tools/applePay.js"
	import payNotice from "@/components/payNotice/payNotice.vue"
	export default {
		components: {
			payNotice
		},
		data() {
			return {
				scrollList: [{
						name: '充值海豚币'
					},
					{
						name: '我的收益',
					}
				],
				current: 0,
				width: 0,
				left: 0,
				itemNode: '',
				payIndex: 1,
				pIndex: 0,
				pId: 0,
				iap_product_id: '',
				cList: [],
				show: false,
				my_moneynum: 0,
				my_scorenum: 0,
				fData: {
					ti_money: '',
					ti_kano: '',
					ti_name: ''
				},
				isAuditMode: true,
			}
		},
		onReady() {
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.tab-item').boundingClientRect(data => {
					this.itemNode = data
					this.width = data[this.current].width
				}).exec();
			}, 500)
		},
		onLoad() {
			this.isAuditMode = getApp().globalData.is_audit_mode
			this.getUserIndex()
			this.getChongzhilist()

			// 初始化苹果支付
			if (this.$isIos) {
				this.applePayInit()
			}
		},
		methods: {
			async getUserIndex() {
				try {
					let result = await this.$request({
						loading: 0,
						method: 'post',
						url: '/api/User/index'
					})
					this.my_moneynum = result.data.data.userinfo.money;
					this.my_scorenum = result.data.data.userinfo.integral;
				} catch (e) {

				}
			},
			async getChongzhilist() {
				try {
					let result = await this.$request({
						loading: 1,
						method: 'post',
						url: "/api/gift/chongzhilist"
					})
					this.cList = result.data.data
					this.pId = this.cList[0].id
					this.iap_product_id = this.cList[0].iap_product_id
					this.show = true
				} catch (e) {}
			},
			xuanze(id, index, iap_id) {
				this.pId = id
				this.pIndex = index
				this.iap_product_id = iap_id
			},
			// 立即充值
			async submitPay() {
				let url = ''
				if (this.payIndex == 1) {
					// #ifdef APP-PLUS
					url = '/api/Payment/wxpay_chong';
					// #endif
					// #ifdef MP-WEIXIN
					url = '/api/Payment/wxpay_chong_xcx';
					// #endif
				} else {
					url = '/api/Payment/alipay_chong';
				}
				try {

					// 安卓
					if (this.$isAndroid) {
						let result = await this.$request({
							loading: 1,
							method: 'post',
							url: url,
							data: {
								id: this.pId
							}
						})
						// #ifdef APP-PLUS
						uni.requestPayment({
							provider: this.payIndex == 1 ? 'wxpay' : 'alipay',
							orderInfo: result.data.data, //支付宝订单数据
							success: (res) => {
								if (res.errMsg == 'requestPayment:ok') {
									this.msg('充值成功')
								} else {
									console.log('fail:' + JSON.stringify(res));
								}
							},
							fail: error => {
								console.log("【requestPayment失败】", error)
								// 微信/支付宝错误码对照https://ask.dcloud.net.cn/article/286
								// 微信
								if (this.payIndex == 1) {
									if (/canceled/g.test(error.errMsg) || /-2/g.test(error.errMsg)) {
										uni.showToast({
											title: "取消支付",
											icon: "none"
										})
										return
									}
									if (/未安装/g.test(error.errMsg) && error.code == -8) {
										uni.showToast({
											title: "请先安装微信",
											icon: "none"
										})
										return
									}

									uni.showModal({
										title: "支付失败",
										content: error.errMsg || "调起支付失败，请稍后重试"
									})
									return
								}

								// 支付宝
								if (/62001/g.test(error.errMsg) || /6001/g.test(error.errMsg)) {
									uni.showToast({
										title: "取消支付",
										icon: "none"
									})
									return
								}

								uni.showModal({
									title: "支付失败",
									content: error.errMsg || "调起支付失败，请稍后重试"
								})
							}
						});
						// #endif
						// #ifdef MP-WEIXIN
						let orderInfo = ''
						if (typeof result.data.data.pay == 'string') {
							orderInfo = JSON.parse(result.data.data.pay)
						}
						uni.requestPayment({
							provider: this.payIndex == 1 ? 'wxpay' : 'alipay',
							...orderInfo, //支付宝订单数据
							success: (res) => {
								if (res.errMsg == 'requestPayment:ok') {
									this.msg('充值成功')
								} else {
									console.log('fail:' + JSON.stringify(res));
								}
							},
							fail: function(err) {
								console.log(err)
							}
						});
						// #endif

						return
					}

					// #ifdef APP-PLUS
					this.handleApplePay()
					// #endif

					// #ifdef H5 || MP-WEIXIN
					uni.showToast({
						title: "请在App端支付",
						icon: "none"
					})
					// #endif
				} catch (e) {
					console.log(e)
					this.msg(e.data.msg)
				}
			},

			// 苹果支付
			async handleApplePay() {
				uni.showLoading({
					title: "请稍后..."
				})

				let result = await this.$request({
					loading: 1,
					method: 'post',
					url: '/api/payment/iap_chong',
					data: {
						id: this.pId
					}
				})

				uni.showLoading({
					title: "正在购买...",
					mask: true
				})

				// console.log("内购下单result--", result)
				if (this.iapChannel) {
					// 调uniapp内购API
					applePay.requestPayment(
						this.iapChannel,
						this.iap_product_id,
						result.data.data.order_no // 订单号
					).then(transaction => {
						// console.log("内购API返回--", transaction)
						uni.showLoading({
							title: "获取结果...",
							mask: true
						})

						this.notifyServerApplyCall(transaction, this.pId).then(() => {
							uni.showToast({
								title: "购买成功",
								duration: 3000
							})
						}).catch(() => {
							uni.showToast({
								title: "获取Apple回调失败，请稍后重试",
								icon: "none",
								duration: 3000
							})
						})

					}).catch(() => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '支付失败'
						})
					})
				} else {
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '当前环境不支持苹果内购支付（缺少iapChannel）'
					})
				}
			},

			// 苹果支付初始化 && 关闭已支付订单
			async applePayInit() {
				this.iapChannel = await applePay.init();
				if (this.iapChannel) {
					applePay.getReview(this.iapChannel).then((transaction) => {
						console.log('【有已支付未回调给后端的订单-丢单】', transaction)

						const findIapItem = this.cList.filter(item => item.iap_product_id == transaction
							.payment.productid)

						if (findIapItem && findIapItem.length) {
							this.notifyServerApplyCall(transaction, findIapItem[0].id).then(() => {
								console.log('【静默补单成功】')
								uni.showToast({
									title: '补单成功',
									icon: "none"
								})
							}).catch(() => {
								console.log('【静默补单失败】')
								uni.showModal({
									title: '温馨提示',
									content: "检测到您充值有掉单情况，请核对充值记录，如充值的海豚币未到账，请联系客服并提供手机号，我们将为您核实后补单。",
									confirmText: '知道了',
									showCancel: false,
									success: () => {
										// 提示过后，将此次可能掉单的订单关闭。不然方法【iapChannel.restoreCompletedTransactions】会一直返回此订单
										applePay.finishTransaction(transaction, this
											.iapChannel)
									}
								})
							})
						}
					})
				}
			},

			/**
			 * 通知后端苹果支付回调 
			 * @param {Number} is_sandbox 是否沙盒模式, 0-否, 1-是
			 * @param {String} product_id 内购商品ID（示例：com.haitunbi.10）
			 * @param {String} order_no 自身订单号（示例：20240415143426668707）
			 * @param {String} trade_no 苹果交易流水号（示例：2000000571828373）
			 * @param {String} transaction_receipt 支付回调信息
			 * 
			 */
			notifyServerApplyCall(transaction, id) {
				return new Promise((resolve, reject) => {
					this.$request({
						loading: 1,
						method: 'post',
						url: '/api/payment/appleInAppPurchasesNotify',
						data: {
							is_sandbox: 0,
							id: id,
							order_no: transaction.payment.username,
							trade_no: transaction.transactionIdentifier,
							transaction_receipt: transaction.transactionReceipt
						}
					}).then((paycall) => {
						console.log("【通知后台苹果支付收据】", paycall)
						applePay.finishTransaction(transaction, this.iapChannel)
						this.getUserIndex()
						resolve()
					}).catch((err) => {
						console.log('【通知后台苹果支付收据Error】', err)
						reject()
					})
				})
			},

			// 提现
			async submitTi() {
				try {
					let result = await this.$request({
						loading: 1,
						method: 'post',
						url: '/api/gift/money_ti',
						data: {
							...this.fData
						}
					})
					console.log(result)
					this.msg(result.data.msg)
				} catch (e) {
					this.msg(e.data.msg)
					//TODO handle the exception
				}
			},

			tabChange(index) {
				this.current = index
				this.left = this.itemNode[index].left
			},
			swiperChange(e) {
				let {
					current
				} = e.detail
				this.current = current
				this.left = this.itemNode[current].left
			},
			selectPay(index) {
				this.payIndex = index
			},
			goRecord() {
				uni.navigateTo({
					url: "/playcenterPage/recharge-record"
				})
			},
			goEarnings() {
				uni.navigateTo({
					url: "/playcenterPage/earnings-detail"
				})
			},
			goWithdrawal() {
				uni.navigateTo({
					url: "/playcenterPage/Withdrawal-details"
				})
			},
			goAddAccout() {
				uni.navigateTo({
					url: "/playcenterPage/add-account"
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif */
		/* #ifndef APP-PLUS */
		height: calc(100vh - 98rpx);

		/* #endif */
		.btn {
			height: 98rpx;
			background: linear-gradient(180deg, #DB89F5 0%, #834BF4 100%);
			border-radius: 49rpx;
			font-size: 32rpx;
			font-weight: 400;
			color: #FFFFFF;
			text-align: center;
			line-height: 98rpx;
			margin-top: 80rpx;

		}

		.navTab {
			display: flex;
			align-items: center;
			height: 98rpx;
			position: relative;
			background-color: #ffffff;

			.tab-item {
				width: 50%;
				text-align: center;
				font-size: 32rpx;
				font-weight: 400;
				color: #333333;
				// margin-right: 56rpx;
			}

			.at-tab-item {

				font-weight: bold;
				color: $uni-text-color;

			}

			.tab-bottom {
				position: absolute;
				bottom: 0;
				transition: left .2s linear;
				display: flex;
				justify-content: center;

				.xian {
					height: 8rpx;
					background: linear-gradient(90deg, #080808 0%, #080808 100%);
					border-radius: 60rpx;
				}
			}
		}

		.swiper {
			flex: 1;

			.scroll-view {
				height: 100%;

				.box {
					padding: 0 30rpx;

					.title {
						display: flex;
						align-items: center;
						justify-content: space-between;
						height: 110rpx;

						.title-left {
							font-size: 32rpx;
							font-weight: 800;
							color: #333333;
						}

						.title-right {
							font-size: 24rpx;
							font-weight: 400;
							color: #333333ad;
							display: flex;
							align-items: center;

							image {
								width: 40rpx;
								height: 40rpx;
							}
						}
					}

					.price-list {
						display: flex;
						flex-wrap: wrap;

						.p-list-item:nth-child(3n) {
							margin-right: 0 !important;
						}

						.p-list-item-pitch {
							border: 1px solid #9D5EF4;

							.tag {
								right: -1px !important;
								top: -1px !important;
							}
						}

						.p-list-item {
							width: 220rpx;
							height: 210rpx;
							background: #ffffff;
							border-radius: 20rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							margin-right: 15rpx;
							margin-bottom: 16rpx;
							position: relative;

							.crystal {
								display: flex;
								align-items: center;

								image {
									width: 48rpx;
									height: 48rpx;
								}

								.p1 {
									font-size: 40rpx;
									font-weight: bold;
									color: #333333;
								}
							}

							.price {
								font-size: 28rpx;
								font-weight: 500;
								color: #333333ad;
								margin-top: 14rpx;
							}

							.tag {
								position: absolute;
								padding: 0 12rpx;
								height: 40rpx;
								background: #F7E1A5;
								border-radius: 0px 20rpx 0px 20rpx;
								right: 0;
								top: 0;
								font-size: 22rpx;
								font-weight: bold;
								color: #7A5B22;
								text-align: center;
								line-height: 40rpx;
							}
						}


					}

					.pay-list {
						font-size: 32rpx;
						font-weight: bold;
						color: #333333;
						padding: 24rpx 24rpx 0 24rpx;
						background: #FFFFFF;
						border-radius: 12rpx;
						margin-top: 9rpx;

						.title {
							height: auto;
						}

						.list {
							.item {
								height: 100rpx;

								.item-left {
									.wxIcon {
										width: 48rpx;
										height: 42rpx;
									}

									.alipayIcon {
										width: 48rpx;
										height: 48rpx;
									}


									text {
										font-size: 28rpx;
										font-weight: 400;
										color: #333333;
										margin-left: 22rpx;
									}
								}

								.item-right {
									image {
										width: 40rpx;
										height: 40rpx;
									}
								}

							}
						}
					}
				}

				.box1 {
					padding: 36rpx 30rpx;

					.earnings-kuai {
						height: 340rpx;
						background: #9796F0;
						border-radius: 20rpx;
						padding: 60rpx 30rpx 0 60rpx;

						.title {
							font-weight: 400;
							color: #FFFFFF;
							display: flex;
							align-items: center;
							justify-content: space-between;

							.title-left {
								font-size: 28rpx;
							}

							.title-right {
								display: flex;
								align-items: center;

								.t1 {
									font-size: 24rpx;
								}

								image {
									width: 40rpx;
									height: 40rpx;
								}
							}
						}

						.price {
							font-size: 72rpx;
							font-weight: bold;
							color: #FFFFFF;
							margin-top: 16rpx;
						}

						.integral {
							font-size: 28rpx;
							font-weight: 400;
							color: #FFFFFF;
							margin-top: 24rpx;
						}
					}

					.label {
						font-size: 26rpx;
						font-weight: 400;
						color: #333333;
						margin-top: 32rpx;
						margin-bottom: 16rpx;
					}

					.input {
						height: 90rpx;
						background: #fff;
						border-radius: 20rpx;
						display: flex;
						align-items: center;
						padding-left: 24rpx;
						color: #333333;
					}

					.p-class {
						font-size: 30rpx;
						font-weight: 400;
						color: #CCCCCC;
					}

					.caution {
						font-size: 26rpx;
						font-weight: 400;
						color: #333333ad;
						margin-top: 24rpx;
						margin-bottom: 36rpx;
					}

					.pay-title {
						font-size: 32rpx;
						font-weight: bold;
						color: #FFFFFF;
					}

					.pay-list {
						display: flex;
						margin-top: 32rpx;

						.left-icon {
							width: 64rpx;
							height: 64rpx;
						}

						.pay-center {
							padding-left: 24rpx;
							flex: 1;

							.pay-label {
								font-size: 32rpx;
								font-weight: 400;
								color: #FFFFFF;
								margin-top: 9rpx;
							}

							.pay-value {
								margin-top: 8rpx;

								text {
									font-size: 26rpx;
									font-weight: 400;
									color: #999999;
								}

								image {
									width: 10rpx;
									height: 17rpx;
									margin-left: 12rpx;
								}
							}
						}

						.right-icon {
							width: 40rpx;
							height: 40rpx;
							margin-top: 9rpx;
						}
					}

					.t-detail {
						display: flex;
						align-items: center;
						justify-content: center;
						margin-top: 48rpx;

						text {
							font-size: 30rpx;
							font-weight: 400;
							color: #333333;
						}

						image {
							width: 12rpx;
							height: 21rpx;
							margin-left: 12rpx;
						}
					}
				}
			}
		}
	}
</style>